package com.itbaizhan.clouddemooauth2server.config;

import com.itbaizhan.clouddemooauth2server.service.impl.JdbcUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.DefaultLoginPageConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


/**
 * 处理用户名和密码校验相关事宜
 */

@Configuration
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Autowired
    private JdbcUserDetailsService  jdbcUserDetailsService;


    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    /**
     * 客户端传递username, password这两个参数到认证授权服务器
     * 验证 username, password的合法性(数据库查询验证或者写死在方法中进行验证)
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication().passwordEncoder(new CustomEncoder())  //指定加密类(明文比较)
//             .withUser("admin") //用户传到后台的用户名
//             .password(new CustomEncoder().encode("123456"))  //对密码加密(明文比较)
//             .roles("admin");
//        auth.inMemoryAuthentication()
//                .withUser("admin") //用户传到后台的用户名
//                .password("123456")  //对密码加密(明文比较)
//                .roles("admin");

        //自定义密码编码器是一种不加密的一种等价写法
        auth.userDetailsService(jdbcUserDetailsService).passwordEncoder(new CustomEncoder());

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.removeConfigurer(DefaultLoginPageConfigurer.class);  //将默认加载的登陆页面配置删除
    }


      //密码编码器, 不解析密码; 只需注入容器, oauth2框架自动完成对前端传来的密码不加密
//    @Bean
//    PasswordEncoder passwordEncoder() {
//        return NoOpPasswordEncoder.getInstance();
//    }

    //密码编码器,解析密码; 只需注入容器, oauth2框架自动完成对前端传来的密码加密
//    @Bean
//    public BCryptPasswordEncoder passwordEncoder(){
//        return new BCryptPasswordEncoder();
//    }

}
